import type { AppRouteModule, AppRouteRecordRaw } from "/@/router/types"
import type { Router, RouteRecordNormalized } from "vue-router"

import { getParentLayout, LAYOUT, IFRAME_BLANK, IFRAME_SIMPLE, EXCEPTION_COMPONENT } from "/@/router/constant"
import { cloneDeep, omit } from "lodash-es"
import { warn, debug } from "/@/utils/log"
import { createRouter, createWebHashHistory } from "vue-router"
import { packageViews } from "/@/utils/monorepo/dynamicRouter"
import { useI18n } from "/@/hooks/web/useI18n"
import { forEach as forEachTree, filter as filterTree } from "/@/utils/helper/treeHelper"

export type LayoutMapKey = "LAYOUT"
const LayoutContent = () => import("/@/layouts/default/content/index.vue")

const LayoutMap = new Map<string, () => Promise<typeof import("*.vue")>>()

LayoutMap.set("LAYOUT", LAYOUT)
LayoutMap.set("IFRAME", IFRAME_BLANK)
//微前端qiankun
LayoutMap.set("LayoutsContent", LayoutContent)

let dynamicViewsModules: Record<string, () => Promise<Recordable>>

// Dynamic introduction
function asyncImportRoute(
  routes: AppRouteRecordRaw[] | undefined,
  parent: AppRouteRecordRaw | undefined,
  root: AppRouteRecordRaw | undefined,
) {
  if (!dynamicViewsModules) {
    dynamicViewsModules = import.meta.glob('../../../**/views/**/*.{vue,tsx}');
    // 跟模块views合并
    dynamicViewsModules = Object.assign({}, dynamicViewsModules, packageViews)
  }
  if (!routes) return
  routes.forEach((item) => {
    //菜单支持国际化翻译
    if (item?.meta?.title) {
      const { t } = useI18n()
      if (item.meta.title.includes("t('") && t) {
        item.meta.title = eval(item.meta.title)
        //console.log('译后: ',item.meta.title)
      }
    }

    if (parent && item.meta.hideMenu) {
      item.meta.hideMenu = true
      //是否隐藏面包屑
      item.meta.hideBreadcrumb = true
      item.meta.currentActiveMenu = parent.path;
    }

    // @ts-ignore 添加忽略路由配置
    if (!item?.route) {
      item.meta.ignoreRoute = true
    }

    // @ts-ignore 添加是否缓存路由配置
    item.meta.ignoreKeepAlive = !item?.meta.keepAlive

    const component = (item.component as string).toUpperCase();
    if (!component || component === 'LAYOUT') {
      item.component = LAYOUT;
    } else if (component === 'IFRAME') {
      item.component = root?.component ? IFRAME_BLANK : IFRAME_SIMPLE;
    } else {
      item.component = dynamicImport(item.component as string);
    }
    if (!item.component || item.component == '') {
      item.component = EXCEPTION_COMPONENT;
      item.props = item.props || {};
      item.props.status = 404;
    }
    item.children && asyncImportRoute(item.children, item, root);
  })
}

export function dynamicImport(component: string, dynamicViewsModules?: Record<string, () => Promise<Recordable>>) {
  if (!dynamicViewsModules) {
    dynamicViewsModules = import.meta.glob('../../../**/views/**/*.{vue,tsx}');
  }
  component = component.replace('.vue', '')
  const keys = Object.keys(dynamicViewsModules)
  const matchKeys = keys.filter((key) => {
    const viewsPath = '/views',
      l = viewsPath.length,
      index = key.indexOf(viewsPath);
    let k = key.substring(index + l);
    const lastIndex = k.lastIndexOf('.');
    k = k.substring(0, lastIndex);
    return k === component;
  });
  if (matchKeys?.length === 1) {
    const matchKey = matchKeys[0]
    return dynamicViewsModules[matchKey]
  } else if (matchKeys?.length > 1) {
    warn(
      "Please do not create `.vue` and `.TSX` files with the same file name in the same hierarchical directory under the views folder. This will cause dynamic introduction failure"
    )
    return
  } else {
    warn('在src/views/下找不到`' + component + '.vue` 或 `' + component + '.tsx`, 请自行创建!');
    return EXCEPTION_COMPONENT
  }
}


// Turn background objects into routing objects
export function transformObjToRoute<T = AppRouteModule>(routeList: AppRouteModule[]): T[] {
  routeList.forEach((item) => {
    const component = (item.component as string).toUpperCase();
    if (component === 'BLANK') {
      item.component = item.path;
      item.children = [cloneDeep(item)];
      item.component = undefined;
    } else {
      item.children = [cloneDeep(item)];
      item.component = LAYOUT;
    }
    item.path = '';
    item.name = `${item.name}Parent`;
    item.meta = item.meta || {};
    item.meta.single = true;
    item.meta.affix = false;
    item.children && asyncImportRoute(item.children, item, item)
  })
  console.log('routeList', routeList)
  return routeList as unknown as T[]
}

/**
 * Convert multi-level routing to level 2 routing
 * 将多级路由转换为 2 级路由
 */
export function flatMultiLevelRoutes(routeModules: AppRouteModule[]) {
  const modules: AppRouteModule[] = cloneDeep(routeModules)
  for (let index = 0; index < modules.length; index++) {
    const routeModule = modules[index]
    // 判断级别是否 多级 路由
    if (!isMultipleRoute(routeModule)) {
      // 声明终止当前循环， 即跳过此次循环，进行下一轮
      continue
    }
    // 路由等级提升
    promoteRouteLevel(routeModule)
  }
  return modules
}

/**
 * 将脱离主框架的路由移动到一级
 */
export const moveMainOutRouteToOneLevel = (routeList: AppRouteModule[]) => {
  const mainOutRouteList: AppRouteModule[] = []
  forEachTree(routeList, (node) => {
    if (node.meta.isMainOut && (!node.children || node.children?.length == 0)) {
      mainOutRouteList.push(node)
    }
  })
  routeList = filterTree(routeList, (node) => {
    return !node.meta.isMainOut
  })

  // const tempMap = new Map<String, AppRouteModule>;
  mainOutRouteList.forEach((node) => {
    routeList.push(node)
  })

  return routeList
}

//提升路由级别
function promoteRouteLevel(routeModule: AppRouteModule) {
  // Use vue-router to splice menus
  // 使用vue-router拼接菜单
  // createRouter 创建一个可以被 Vue 应用程序使用的路由实例
  let router: Router | null = createRouter({
    routes: [routeModule as unknown as RouteRecordNormalized],
    history: createWebHashHistory(),
  })
  // getRoutes： 获取所有 路由记录的完整列表, 过滤掉名字是undefined的, 避免死循环
  const routes = router.getRoutes().filter((e) => e.name)

  // 将所有子路由添加到二级路由
  addToChildren(routes, routeModule.children || [], routeModule)
  router = null

  // omit lodash的函数 对传入的item对象的children进行删除
  routeModule.children = routeModule.children?.map((item) => omit(item, "children"))
}

// Add all sub-routes to the secondary route
// 将所有子路由添加到二级路由
function addToChildren(routes: RouteRecordNormalized[], children: AppRouteRecordRaw[], routeModule: AppRouteModule) {
  for (let index = 0; index < children.length; index++) {
    const child = children[index]
    const route = routes.find((item) => item.name === child.name)
    if (!route) {
      continue
    }
    routeModule.children = routeModule.children || []
    if (!routeModule.children.find((item) => item.name === route.name)) {
      routeModule.children?.push(route as unknown as AppRouteModule)
    }
    if (child.children?.length) {
      addToChildren(routes, child.children, routeModule)
    }
  }
}

// Determine whether the level exceeds 2 levels
// 判断级别是否超过2级
function isMultipleRoute(routeModule: AppRouteModule) {
  // Reflect.has 与 in 操作符 相同, 用于检查一个对象(包括它原型链上)是否拥有某个属性
  if (!routeModule || !Reflect.has(routeModule, "children") || !routeModule.children?.length) {
    return false
  }

  const children = routeModule.children

  let flag = false
  for (let index = 0; index < children.length; index++) {
    const child = children[index]
    if (child.children?.length) {
      flag = true
      break
    }
  }
  return flag
}
/**
 * 组件地址前加斜杠处理
 */
export function addSlashToRouteComponent(routeList: AppRouteRecordRaw[]) {
  routeList.forEach((route) => {
    const component = route.component as string
    if (component) {
      const layoutFound = LayoutMap.get(component.toUpperCase())
      if (!layoutFound) {
        route.component = component.startsWith("/") ? component : `/${component}`
      }
    }
    route.children && addSlashToRouteComponent(route.children)
  })
  return routeList as unknown as T[]
}

export function getRouteAllPath(routes: AppRouteRecordRaw[]) {
  const paths: string[] = [];

  routes.forEach((route) => {
    if (route.children && route.children.length > 0) {
      route.children.forEach(children => {
        if (children.path.startsWith('/')) {
          paths.push(`/${children.path}`.replaceAll('//', '/'))
        } else {
          paths.push(('/' + route.path + '/' + children.path).replaceAll('//', '/'))
        }
      })
    } else {
      paths.push(('/' + route.path).replaceAll('//', '/'))
    }
  });
  return paths;
}
